var express = require("express");
var router = express.Router();
var bodyParser = require("body-parser");
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false })
    //加密
var crypto = require("crypto");

router.get("/session", function(req, res) {
    if (req.session.isVisit) {
        console.log(req.session);
        res.send("欢迎再次访问");
    } else {
        req.session.isVisit = 1;
        res.send("欢迎第一次访问");
    }
});
var user = [{ "username": "hello", "password": "123567" }];

router.get("/login", function(req, res) {
    res.render("login.hbs");
});
router.post("/login", urlencodedParser, function(req, res) {
    //用md5加密以下我们密
    var md5 = crypto.createHash("md5");
    md5.update(user[0].password);
    var sign = md5.digest("hex");
    if (req.body.username == user[0].username) {
        var password = req.body.password;
        var md5 = crypto.createHash("md5");
        md5.update(password);
        var verifysign = md5.digest("hex");
        if (verifysign == sign) {
            // res.session.islogin = true;
            req.session.username = req.body.username;
            res.redirect("/main");
        } else {
            res.redirect("/login");
            console.log("登录失败");
        }
    }
})
router.get("/main", function(req, res) {
    res.render("main.hbs", {
        user: { name: req.session.username },
        islogin: req.session.islogin,
        layout: "other"
    });
});
module.exports = router;